package com.android.superobstacleavoider;

import android.content.Context;

import com.android.superobstacleavoider.framework.Audio;


public class GameUpdater implements Runnable {

	private Thread m_thread = null;
	private boolean m_firstTime = true;
	// private Screen screens[] = null;

	private long m_time;
	private boolean m_isRunning;
	private Level m_level;
	private HUD m_hud;
	private LookAtCamera m_camera;
	
	public GameUpdater(Context a_context, Level a_level, HUD a_hud, LookAtCamera a_camera,
			Audio a_audio) {
		m_level = a_level;
		m_thread = new Thread(this);
		m_isRunning = true;
		m_time = System.currentTimeMillis();
		m_hud = a_hud;
		m_camera = a_camera;
	}

//Update the logic of the game
private void update() {
   
   //Calculate delta time (Time since last update)
   float deltaTime = new Float(System.currentTimeMillis() - m_time) / 1000;
   
   //Update current time
   m_time = System.currentTimeMillis();
   
   // Update level
   m_level.update(deltaTime);
   
   //Update hud
   if (m_level.playerIsAlive())
     m_hud.update(deltaTime, m_level.getScore());
     
   // update camera
   m_camera.setPosX(m_level.getPlayer().getPos().X);
   m_camera.setLookAtX(m_level.getPlayer().getPos().X);		
}

	public void run() {
		while (m_isRunning) {			
			try {
				if(m_firstTime)
				{
					Thread.sleep(2000);
					m_firstTime = false;
				}
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			update();
		}
	}

	public void onPause() {
		m_isRunning = false;
		AudioHandler.getMusic().pause();
		m_thread.stop();
	}

	public void onResume() {
		m_isRunning = true;
		if(AudioHandler.getMusic() != null)
			AudioHandler.playMusic(AudioHandler.getMusic());
		m_thread.resume();
	}

	public void startThread() {
		m_thread.start();
	}
}
